import {Component, OnInit} from '@angular/core';
import { ImagePicker } from '@ionic-native/image-picker/ngx';
import {HttpService} from '../../service/http.service';
import {ToastService} from '../../service/toast.service';
import {ModalController, NavController, PopoverController} from '@ionic/angular';
import {RegionPickModelComponent} from '../../components/region-pick-model/region-pick-model.component';
import {RadioPickModelComponent} from '../../components/radio-pick-model/radio-pick-model.component';
import {CheckPickModelComponent} from '../../components/check-pick-model/check-pick-model.component';
import {CalendarModelComponent} from '../../components/calendar-model/calendar-model.component';
import {FilterListComponent} from '../../components/filter-list/filter-list.component';
import {WechatService} from '../../service/wechat.service';
import {AgentModelComponent} from '../../components/agent-model/agent-model.component';
import {ServiceModelComponent} from '../../components/service-model/service-model.component';
import {FileChooser} from '@ionic-native/file-chooser/ngx';
import {TransferService} from '../../service/transfer.service';
import {FileService} from '../../service/file.service';
import { NetworkInterface } from '@ionic-native/network-interface/ngx';
import {HttpBase} from '../../service/http.base';
declare var Wechat: any;

@Component({
    selector: 'app-test',
    templateUrl: './test.page.html',
    styleUrls: ['./test.page.scss'],
})
export class TestPage implements OnInit {

    testTitle = 'APP_TITLE';
    checkedList: Array<string> = [];
    selectValue = null;
    filterList = [
        { label: '区域', value: 'region' },
        { label: '医院', value: 'hospital' },
        { label: '科室', value: 'department' },
    ];

    orderId = null;
    envIndex = HttpBase.EnvIndex;

    constructor(
        private navCtrl: NavController,
        private imagePicker: ImagePicker,
        private fileChooser: FileChooser,
        private networkInterface: NetworkInterface,
        private httpService: HttpService,
        private toastSrv: ToastService,
        private wechatSrv: WechatService,
        private transferSrv: TransferService,
        private fileSrv: FileService,
        private modalController: ModalController,
        private popoverController: PopoverController
    ) {

    }

    ngOnInit() {

    }

    onEntrySetting() {
        this.navCtrl.navigateForward('settings');
    }

    async onPopoverClick() {
        const popover = await this.popoverController.create({
            component: FilterListComponent,
            cssClass: 'custom-popover',
            componentProps: {
                filterList: this.filterList,
                checkedList: this.checkedList
            }
        });
        await popover.present();
        const { data } = await popover.onDidDismiss();
        if (data) {
            const { checkedArray, filterResult } = data;
            this.checkedList = checkedArray.filter(item => item.checked).map(item => item.value);
            console.log('onPopoverClick:', filterResult);
        }
    }

    public async onButtonClick1() {
        const result = await this.httpService.get()
            .setUrl('http://39.100.112.123:9210/api/pub/source/hospitalList?listType=simple')
            .request();
        alert(JSON.stringify(result));
    }

    public async onButtonClick2() {
        const result = await this.httpService.get()
            .setUrl('https://www.erc.ink/api/hello')
            .request();
        alert(JSON.stringify(result));
    }

    public async onButtonClick3() {
        const result = await this.httpService.get()
            .setUrl('http://47.107.99.148:9090/api/hello')
            .request();
        alert(JSON.stringify(result));
    }

    public async onButtonClick4() {
        const result: any = await this.httpService.get()
            .setPath('/user/doctorList')
            .setQuery({
                doctorState: 1,
            })
            .request();

        console.log('result:', result);
    }

    public async onButtonClick5() {
        this.toastSrv.setColor(this.toastSrv.colorArray[2]).setPosition('center').showToast('hello world');
    }

    public async onButtonClick6() {
        const result: any = await this.httpService.get()
            .setPath('/pub/source/threeRegionData')
            .setQuery({
                style: 'tree'
            })
            .request();

        if (result.status === 0) {
            const modal = await this.modalController.create({
                component: RegionPickModelComponent,
                componentProps: {
                    title: '区域选择',
                    itemArray: [
                        {
                            name: '选择国家',
                            type: 1,
                        },
                        {
                            name: '选择州',
                            type: 2,
                        },
                        {
                            name: '选择城市',
                            type: 3
                        },
                    ],
                    dataArray: [ ...result.data ]
                }
            });
            await modal.present();
            const { data } = await modal.onDidDismiss();
            console.log('resultArray:', data);
        }
    }

    public async onButtonClick7(event) {
        if (event === 1) {
            const result: any = await this.httpService.get()
                .setPath('/pub/source/hospitalList')
                .setQuery({ listType: 'simple' })
                .request();
            console.log(result.data);
            if (result.status === 0) {
                const modal = await this.modalController.create({
                    component: CheckPickModelComponent,
                    componentProps: {
                        title: '区域选择',
                        dataList: [ ...result.data ],
                        checkedList: this.checkedList
                    }
                });
                await modal.present();
                const { data } = await modal.onDidDismiss();
                if (data) {
                    this.checkedList = data;
                    console.log('resultArray:', data);
                }
            }
        } else if (event === 2) {
            const result: any = await this.httpService.post()
                .setPath('/pub/source/departmentList')
                .request();
            if (result.status === 0) {
                const modal = await this.modalController.create({
                    component: RadioPickModelComponent,
                    componentProps: {
                        title: '区域选择',
                        labelProp: 'name',
                        dataList: [ ...result.data ],
                        selectValue: this.selectValue
                    }
                });
                await modal.present();
                const { data } = await modal.onDidDismiss();
                if (data) {
                    this.selectValue = data.value;
                    console.log('resultArray:', data);
                }
            }
        }
    }

    public async onButtonClick8() {
        const modal = await this.modalController.create({
            component: CalendarModelComponent,
            componentProps: {
                title: '日期选择',
                timeRange: false
            }
        });
        await modal.present();
        const { data } = await modal.onDidDismiss();
        console.log('resultArray:', data);
    }

    public async onButtonClick9(event) {
        try {
            switch (event) {
                case 1:
                    const isInstall = await this.wechatSrv.wechatIsInstall();
                    alert('Wechat installed: ' + (isInstall ? 'Yes' : 'No'));
                    break;

                case 2:
                    const authResult: any = await this.wechatSrv.wechatAuthLogin();
                    if (authResult.code) {
                        const result: any = await this.httpService.post()
                            .setPath('/pub/user/wxLogin')
                            .setBody({
                                wxCode: authResult.code
                            })
                            .request();
                        alert(JSON.stringify(result));
                    }
                    break;
            }
        } catch (e) {
            alert('Failed:' + e);
        }
    }

    public async onPopoverClick1() {
        const model = await this.modalController.create({
            component: AgentModelComponent,
            cssClass: 'agent-model',
            componentProps: {
                doctorPhone: '8899174'
            }
        });
        await model.present();
        const { data } = await model.onDidDismiss();
    }

    public async onPopoverClick2() {
        const model = await this.modalController.create({
            component: ServiceModelComponent,
            cssClass: 'service-model'
        });
        await model.present();
        const { data } = await model.onDidDismiss();
    }

    public async onPictureSelect() {
        try {
            const result = await this.imagePicker.getPictures({ maximumImagesCount: 1 });
            alert(JSON.stringify(result));
            const uploadResult = await this.transferSrv.setPath('/pub/upload/file')
                .setFile(result)
                .parseFile()
                .setFieldName('user')
                .setFileName('avatar.jpg')
                .setParams({
                    uploadType: 'avatar',
                    userId: 12
                })
                .upload();
            alert(uploadResult.data.resUrl);
        } catch (e) {
            alert(JSON.stringify(e));
        }
    }

    public async onFileSelect() {
        try {
            const videoContent = await this.fileSrv.openFileChooser({ mime: 'video/*' });
            alert(videoContent);
            const videoPath = await this.fileSrv.resolveFileContent(videoContent);
            alert(videoPath);
            const result = await this.transferSrv.setPath('/pub/upload/file')
                .setFile(videoPath)
                .parseFile()
                .setFieldName('user')
                .setParams({
                    uploadType: 'video', // avatar/video/attach
                    userId: 38
                })
                .upload();
            alert(JSON.stringify(result));
        } catch (e) {
            alert(JSON.stringify(e));
        }
    }

    public async onNetworkTest() {
        this.networkInterface.getWiFiIPAddress()
            .then(address => alert(`getWiFiIPAddress IP: ${address.ip}, Subnet: ${address.subnet}`))
            .catch(error => alert(`getWiFiIPAddress Unable to get IP: ${error}`));

        this.networkInterface.getCarrierIPAddress()
            .then(address => alert(`getCarrierIPAddress IP: ${address.ip}, Subnet: ${address.subnet}`))
            .catch(error => alert(`getCarrierIPAddress Unable to get IP: ${error}`));
    }

    private async unifiedOrderRequest(price) {
        const result: any = await this.httpService.post()
            .setPath('/pub/order/wxUnifiedOrder')
            .setBody({
                orderId: this.orderId,
                paymentPrice: price
            })
            .request();

        if (result.status === 0) {
            return result.data;
        } else {
            throw new Error(result.message);
        }
    }

    private async updateOrderPayment(tradeCode) {
        const result: any = await this.httpService.get()
            .setPath('/pub/order/wxQueryOrder')
            .setQuery({
                tradeCode
            })
            .request();

        if (result.status === 0) {
            return result.data;
        } else {
            throw new Error(result.message);
        }
    }

    public async onWxPaymentRequest() {
        try {
            const prepayResult = await this.unifiedOrderRequest(0.01);
            await this.wechatSrv.wechatPaymentRequest(prepayResult);
            await this.updateOrderPayment(prepayResult.trade_code);
        } catch (e) {
            alert('error: ' + JSON.stringify(e));
        }
    }
}
